/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.parser.markup;

import java.util.LinkedList;

import moxl.parser.markup.types.CloseElementTagMarkup;
import moxl.parser.markup.types.OpenElementTagMarkup;

public class WellFormedTracker
{
	LinkedList<OpenElementTagMarkup> elementMarkupStack;

	public void accept(Markup markup) throws NotWellFormedException
	{
		if (markup instanceof OpenElementTagMarkup)
		{
			processOpenElementTagMarkup((OpenElementTagMarkup) markup);
		}
		else if (markup instanceof CloseElementTagMarkup)
		{
			processCloseElementTagMarkup((CloseElementTagMarkup) markup);
		}
	}

	void processOpenElementTagMarkup(OpenElementTagMarkup markup) throws NotWellFormedException
	{
		if (elementMarkupStack == null)
		{
			elementMarkupStack = new LinkedList<OpenElementTagMarkup>();
			if (!markup.isEmpty())
			{
				elementMarkupStack.addLast(markup);
			}
		}
		else if (elementMarkupStack.isEmpty())
		{
			throw new NotWellFormedException("Document cannot contain more than one root element", markup.getFirstToken().getLocation());
		}
		else
		{
			if (!markup.isEmpty())
			{
				elementMarkupStack.addLast(markup);
			}
		}
	}

	void processCloseElementTagMarkup(CloseElementTagMarkup closingMarkup) throws NotWellFormedException
	{
		if (elementMarkupStack == null)
		{
			throw new NotWellFormedException("Document cannot start with a closing tag", closingMarkup.getFirstToken().getLocation());
		}
		else if (elementMarkupStack.isEmpty())
		{
			throw new NotWellFormedException("Unexpected closing tag", closingMarkup.getFirstToken().getLocation());
		}
		else
		{
			OpenElementTagMarkup openingMarkup = (OpenElementTagMarkup) elementMarkupStack.removeLast();
			if (!openingMarkup.getTagName().equals(closingMarkup.getTagName()))
			{
				throw new NotWellFormedException("Closing tag at " + closingMarkup.getFirstToken() + " does not match opening tag", openingMarkup
				        .getFirstToken().getLocation());
			}
		}
	}

	public boolean isWellFormed()
	{
		return elementMarkupStack != null && elementMarkupStack.isEmpty();
	}

}
